package ar.edu.uba.fi.jmit.monitorengine.backend.server;
import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

import ar.edu.uba.fi.jmit.monitorengine.parser.ParsersManager;

/**
 * Esta clase es la que se encarga de recibir los request
 * cuando se sube un archivo, y guardarlo donde corresponda.
 * @author Cristian
 *
 */
public class UploadServlet extends UploadAction {

	private static final long serialVersionUID = -2552590592237850850L;

	@Override
	public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {
		String response = "";
		int cont = 0;
		for (FileItem item : sessionFiles) {
			if (false == item.isFormField()) {
				cont++;
				try {
					String[] filePathName = item.getName().split("/");
					ParsersManager.loadFile(item.getString(), filePathName[filePathName.length - 1]);

					response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n";
					response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n";
					response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n";
					response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n";
				} catch (Exception e) {
					throw new UploadActionException(e);
				}
			}
		}

		removeSessionFileItems(request);

		return "<response>\n" + response + "</response>\n";
	}
}